package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.domain.Member;
import com.itheima.domain.Order;
import com.itheima.domain.Setmeal;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @Reference
    private OrderService orderService;

    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        //手机登录3次
        //cookie有效期设置

        String telephone = (String) map.get("telephone");//从页面获取手机号
        String validateCode = (String) map.get("validateCode");//从页面获取验证码
        //从redis中获取保存的验证
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //对两个验证码进行判断
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码输入正确
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            //如果member为空,说明不是会员,自动注册
            if (member == null) {
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //member 不为空 说明是会员 进行下一步
            //向客户端浏览器写入cookie,内容为手机号
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE,30);
            Date tokenOutTime = instance.getTime();
            String s = null;
            try {
                s = DateUtils.parseDate2String(tokenOutTime,"yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String cv = telephone + "&" + s;
            Cookie cookie = new Cookie("login_member_telephone", telephone);//新建cookie
            cookie.setPath("/");//设置cookie路径
            cookie.setMaxAge(60 * 60 * 24 * 30);//设置cookie最大存活时间
            response.addCookie(cookie);
            //将会员信息保存到 redis
            String json = JSON.toJSON(member).toString();
            resource.setex(telephone,60*30,json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }else{
            //验证码输入错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //通过手机号查询会员
    @RequestMapping("/findByTelephone")
    public Result findByTelephone(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals("login_member_telephone")){
                String telephone = cookie.getValue();
                Member member = memberService.findByTelephone(telephone);
                return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,member);
            }
        }
        return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
    }
    //修改会员信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member){
        try {
            memberService.update(member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
    }
    //通过会员id查询套餐信息
    @RequestMapping("/findSetmealById")
    public Result findSetmealById(Integer id){
        try {
            List<Setmeal> list = orderService.findSetmealById(id);
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }
    //通过会员id和日期查询套餐信息
    @RequestMapping("/findSetmealByIdAndDate")
    public Result findSetmealByIdAndDate(@RequestBody Map map){
        String memberId = (String) map.get("id");
        String startDate = (String) map.get("startDate");
        if (startDate == null){
            startDate = "1970-00-01";
        }
        String endDate = (String) map.get("endDate");
        if (endDate == null){
            endDate = DateUtils.getToday().toString();
        }
        try {
            List<Setmeal> list = orderService.findSetmealByIdAndDate(memberId,startDate,endDate);
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    //通过会员id查询会员信息
    @RequestMapping("/findMemberById")
    public Result findMemberById(String id){
        try {
            Member member = memberService.findMemberById(id);
            return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    @RequestMapping("/edit2Telephone")
    public Result edit2Telephone(@RequestBody Map map){
        String telephone = (String) map.get("telephone");//从页面获取手机号
        String validateCode = (String) map.get("validateCode");//从页面获取验证码
        String id = (String) map.get("id");
        //从redis中获取保存的验证
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_CHANGPHONE);
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码输入正确
            //修改手机号
            memberService.edit2Telephone(id,telephone);
            return new Result(true, MessageConstant.EDIT_MEMBER_PHONE_SUCCESS);
        }else{
            //验证码输入错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

    }

    //使用手机号和验证码登录
    @RequestMapping("/getsetmealListByPhoneNumber")
    public Result getsetmealListByPhoneNumber(HttpServletRequest request) {
        try {
            //获取手机号
            String phoneNumber = (String) request.getSession().getAttribute("phoneNumber");
            if (phoneNumber == null || phoneNumber=="") {
                phoneNumber = "15236320397";
               // return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
            }
            System.out.println(phoneNumber);
            //根据手机号查询会员信息
            List<Map> map =  memberService.getsetmealListByPhoneNumber(phoneNumber);
            //查询成功,返回结果
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();

            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }
}
